<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="统一社会信用代码" prop="certNo">
        <el-input
          v-model="queryParams.certNo"
          placeholder="请输入统一社会信用代码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customName">
        <el-input
          v-model="queryParams.customName"
          placeholder="请输入客户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务类型" prop="busiType">
        <el-select
          v-model="queryParams.busiType"
          clearable
          multiple
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['client:service:query']" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:service:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:service:delete']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="selected.length === 0"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:service:import']"
          type="success"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="$refs.file.click()"
        >导入</el-button>
        <input ref="file" type="file" style="display: none" @change="handleUpload">
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:service:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDownload"
        >导入模板下载</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="clientList"
      @selection-change="(selection) => selected = selection"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户统一社会信用代码" prop="certNo" />
      <el-table-column label="客户名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="行业分类" width="130">
        <template slot-scope="scope">
          <el-tag
            v-for="item in scope.row.busiType.split(',')"
            :key="item"
            :type="getDictClass('sys_business_type', item)"
            size="mini"
            class="busi-tag"
          >{{ dict.label.sys_business_type[item] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="企业联系人" prop="linkName" width="100" />
      <el-table-column label="企业联系电话" prop="linkTel" width="100" />
      <el-table-column label="客户业务" prop="flag" width="120" />
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="最近服务时间" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastServiceTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['client:service:update']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['client:service:delete']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            v-hasPermi="['client:service:view']"
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="goDetailPage(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="客户名称" prop="corp">
          <el-select
            v-model="form.corp"
            filterable
            remote
            placeholder="请输入关键词查询"
            :remote-method="searchCorp"
            :loading="searchLoading"
            @change="changeCorp"
          >
            <el-option
              v-for="item in searchingCorpList"
              :key="item.id"
              :label="item.name"
              :value="item.corp"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="certNo">
          <el-input v-model="form.certNo" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="业务类型" prop="busiType">
          <el-select
            v-model="form.busiType"
            multiple
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.sys_business_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人">
          <el-input v-model="form.linkName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.linkTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClient, searchClient, getClient, delClient, addClient, updateClient, importClient } from '@/api/client/client'

export default {
  name: 'ClientList',
  dicts: ['sys_business_type'],
  data() {
    return {
      loading: true,
      // 选中数组
      selected: [],
      showSearch: true,
      clientList: [],
      total: 0,

      // 弹出层标题
      title: '',
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certNo: undefined,
        customName: undefined,
        busiType: undefined
      },

      // 表单参数
      searchLoading: false,
      searchingCorpList: [],
      form: {},
      rules: {
        certNo: [
          { required: true, message: '客户信用代码不能为空', trigger: 'blur' }
        ],
        corp: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      const query = {
        ...this.queryParams,
        busiType: (this.queryParams.busiType || []).join(',')
      }
      listClient(query).then(response => {
        this.clientList = response.data.records
        this.total = response.data.total
        this.loading = false
      }
      )
    },
    searchCorp(query) {
      const params = {
        corpName: query
      }
      this.searchLoading = true
      searchClient(params).then(response => {
        const data = response.data.data.hits.hits.map(item => {
          const id = item._id
          const name = item._source.COMPANY_NM
          const certNo = item._source.ORGNUM
          return {
            id,
            name,
            corp: certNo ? `${name}/${certNo}` : name
          }
        })
        this.searchingCorpList = data
        this.searchLoading = false
      })
    },
    changeCorp(corp) {
      const certNo = corp.includes('/') ? corp.split('/')[1] : null
      this.form.certNo = certNo || this.form.certNO
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加客户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getClient(row.id).then(response => {
        const { lastServiceTime, busiType } = response.data
        this.form = {
          ...response.data,
          corp: response.data.name,
          lastServiceTime: lastServiceTime ? new Date(lastServiceTime) : null,
          busiType: busiType.split(',')
        }
        this.open = true
        this.title = '修改客户信息'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const formData = {
            id: '',
            ...this.form,
            name: this.form.corp.split('/')[0],
            busiType: (this.form.busiType || []).join(',')
          }
          delete formData.corp
          if (this.form.id) {
            updateClient(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addClient(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.selected.map(v => v.id)
      this.$modal.confirm(`确认删除 ${row.id ? row.name : '所选'} 数据？`).then(function() {
        return delClient(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
        this.$refs.table.clearSelection()
        this.selected = []
      }).catch(() => {})
    },
    // 导入
    async handleUpload(event) {
      const data = new FormData()
      data.append('file', event.target.files[0])
      await importClient(data)
      this.getList()
      this.$refs.file.value = null
    },
    // 导出过滤后的企业数据
    handleExport() {
      const query = {
        ...this.queryParams,
        busiType: (this.queryParams.busiType || []).join(',')
      }
      this.download('corpBasicInfo/export', query, `corp_${new Date().getTime()}.xlsx`)
    },
    // 下载模板
    handleDownload() {
      this.download('corpBasicInfo/importTemplate', {}, `client_template.xlsx`)
    },
    goDetailPage(row) {
      this.$router.push({
        name: 'ClientDetail',
        params: {
          id: row.id,
          certNo: row.certNo,
          busiType: row.busiType
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.busi-tag + .busi-tag {
  margin-left: 5px;
}
</style>
